package dmir.reaction.publico.graph.neo4j;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class GraphMLParser extends DefaultHandler {
	
	boolean getData = false;
	boolean inEdge = false;
	boolean inURL = false;
	String data;
	String time;
	String id1;
	String id2;
	
	Set<Article> articles = new HashSet<Article>();
	LinkedList<MyRelationship> relationships;
	 	
	
	public GraphMLParser(LinkedList<MyRelationship> edges) {
		super();
		this.relationships = edges;
	}

	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		
		if (qName.equalsIgnoreCase("edge")) {
			getData = true;	
			inEdge = true;			
			id1 = attributes.getValue(1);
			id2 = attributes.getValue(2);
		}
		
		if (qName.equalsIgnoreCase("data")) {
			if (attributes.getValue(0).equalsIgnoreCase("d4")) {
				inURL = true;
			}			
		}
		
		if (qName.equalsIgnoreCase("cooccurrence")) {
			if (inURL) {
				getData=true;
				Article a = new Article(attributes.getValue(0), attributes.getValue(1), attributes.getValue(2), attributes.getValue(3), Integer.parseInt(attributes.getValue(4)));
				articles.add(a);
			}
		}
	}

	public void characters(char ch[], int start, int length) throws SAXException {
		if (getData)
			this.data = new String(ch, start, length);
	}
	
	public void endElement(String uri, String localName, String qName) throws SAXException {		
		
		if (qName.equalsIgnoreCase("edge")) {			
			inEdge = false;
			getData = false;
			MyRelationship r = new MyRelationship(articles, Long.parseLong(id1), Long.parseLong(id2));						
			relationships.add(r);			
			articles.clear();
		}
	}
}








